package x.ovo.wechat.bot;

import lombok.extern.slf4j.Slf4j;
import x.ovo.wechat.bot.common.command.Command;
import x.ovo.wechat.bot.common.command.CommandExecutor;
import x.ovo.wechat.bot.common.entity.message.TextMessage;
import x.ovo.wechat.bot.common.plugin.Plugin;

import java.util.Arrays;

@Slf4j
public class StatisticsCommandExecutor extends CommandExecutor {


    public StatisticsCommandExecutor(Plugin plugin) {
        super(plugin);
        plugin.getUsers().addAll(plugin.getDescription().getAuthors());
        plugin.getUsers().addAll(plugin.getConfig().getList("users").stream().map(Object::toString).toList());
    }

    @Override
    public void execute(Command command, TextMessage message) {
        String fromName = command.getFromName();
        String[] args = command.formatArgs();

        if (!inAuthors(fromName)) {
            this.context.getApi().sendText(message.getFromUser().getUserName(), "你没有权限执行此命令，不要调皮");
            return;
        }

        try {
            if (args.length == 0 || args[0].equals("help")) {
                this.context.getApi().sendText(message.getFromUser().getUserName(), help());
            } else if (args[0].equals("add")) {
                this.context.getApi().sendText(message.getFromUser().getUserName(), add(args[1]));
            } else if (args[0].equals("remove")) {
                this.context.getApi().sendText(message.getFromUser().getUserName(), remove(args[1]));
            } else {
                this.context.getApi().sendText(message.getFromUser().getUserName(), "未知命令");
            }
        } catch (Exception e) {
            log.error("命令执行失败", e);
            this.context.getApi().sendText(message.getFromUser().getUserName(), "命令执行失败" + e.getMessage());
        }
    }

    private String help() {
        return """
                [群消息统计]插件帮助：
                help                显示帮助
                add [user...]       添加用户
                remove [user...]    移除用户
                """;
    }

    private String add(String... users) {
        this.plugin.getUsers().addAll(Arrays.stream(users).toList());
        this.plugin.getConfig().set("users", this.plugin.getUsers());
        this.plugin.saveConfig();
        return "添加 " + Arrays.toString(users) + " 成功";
    }

    private String remove(String... users) {
        Arrays.stream(users).toList().forEach(this.plugin.getUsers()::remove);
        this.plugin.getConfig().set("users", this.plugin.getUsers());
        this.plugin.saveConfig();
        return "移除 " + Arrays.toString(users) + " 成功";
    }

}
